from flask import request, jsonify, session, redirect, url_for, make_response

from models import db
from models.index import User
from views import passport_bp


@passport_bp.route('/passport/register', methods=['GET', 'POST'])
def register():
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    image_code = request.json.get("image_code")
    smscode = request.json.get("smscode")
    image = session.get('image_code')
    if_user = db.session.query(User).filter(User.mobile == mobile).first()

    if if_user:
        ret = {
            'errno': 1001,
            'errmsg': '该手机号已经存在!'
        }
    elif image_code.lower() != image.lower():
        ret = {
            'errno': 1002,
            'errmsg': '验证码不正确!'
        }
    else:
        user = User()
        user.nick_name = mobile
        user.password_hash = password
        user.mobile = mobile
        try:
            db.session.add(user)
            db.session.commit()
            session['user_id'] = user.id
            session['nick_name'] = mobile
            ret = {
                'errno': 0,
                'errmsg': '注册成功'
            }

        except Exception as ret1:
            db.session.rollback()
            ret = {
                'errno': 1003,
                'errmsg': '注册失败,请重试！'
            }

    return jsonify(ret)


@passport_bp.route('/passport/login', methods=['GET', 'POST'])
def login():
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    user = db.session.query(User).filter(User.mobile == mobile, User.password_hash == password).first()
    if user:
        ret = {
            'errno': 0,
            'errmsg': '登录成功'
        }
        session['user_id'] = user.id
        session['nick_name'] = mobile
    else:
        ret = {
            'errno': 2001,
            'errmsg': '用户名或密码错误!'

        }
    return jsonify(ret)


@passport_bp.route('/passport/logout')
def logout():
    session.clear()
    return redirect(url_for('index.index'))


@passport_bp.route("/passport/image_code")
def image_code():
    from utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    session['image_code'] = text

    # 返回响应内容
    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/png'

    return resp
